import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class CarRentalSystem extends JFrame {
    private Connection connect() {
        try {
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/car_rental_system", "root", "");
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "数据库连接失败: " + e.getMessage());
            return null;
        }
    }

    public CarRentalSystem() {
        setTitle("汽车租赁信息管理系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 400);
        setLocationRelativeTo(null);
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("汽车登记", createRegisterPanel());
        tabbedPane.addTab("租赁管理", createRentPanel());
        tabbedPane.addTab("归还管理", createReturnPanel());
        tabbedPane.addTab("查询功能", createSearchPanel());
        add(tabbedPane);
        setVisible(true);
    }

    private JPanel createRegisterPanel() {
        JPanel panel = new JPanel(new GridLayout(0, 2, 10, 10));
        JTextField txtId = new JTextField(), txtBrand = new JTextField(), txtModel = new JTextField(), txtYear = new JTextField(), txtRent = new JTextField();
        JButton btnSubmit = new JButton("提交");
        panel.add(new JLabel("汽车编号:"));
        panel.add(txtId);
        panel.add(new JLabel("品牌:"));
        panel.add(txtBrand);
        panel.add(new JLabel("型号:"));
        panel.add(txtModel);
        panel.add(new JLabel("年份:"));
        panel.add(txtYear);
        panel.add(new JLabel("每日租金:"));
        panel.add(txtRent);
        panel.add(btnSubmit);
        btnSubmit.addActionListener(e -> {
            registerCar(txtId.getText(), txtBrand.getText(), txtModel.getText(),
                    Integer.parseInt(txtYear.getText()),
                    Double.parseDouble(txtRent.getText()));
        });
        return panel;
    }

    private void registerCar(String id, String brand, String model, int year, double dailyRent) {
        String sql = "INSERT INTO cars (id, brand, model, year, daily_rent) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, id);
            pstmt.setString(2, brand);
            pstmt.setString(3, model);
            pstmt.setInt(4, year);
            pstmt.setDouble(5, dailyRent);
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "汽车信息登记成功");
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "登记失败: " + e.getMessage());
        }
    }

    private JPanel createRentPanel() {
        JPanel panel = new JPanel(new GridLayout(0, 2, 10, 10));
        JTextField txtCarId = new JTextField(), txtName = new JTextField(), txtContact = new JTextField(),
                txtStartDate = new JTextField();
        JButton btnRent = new JButton("租出");
        panel.add(new JLabel("汽车编号:"));
        panel.add(txtCarId);
        panel.add(new JLabel("客户姓名:"));
        panel.add(txtName);
        panel.add(new JLabel("联系方式:"));
        panel.add(txtContact);
        panel.add(new JLabel("起租日期:"));
        panel.add(txtStartDate);
        panel.add(btnRent);
        btnRent.addActionListener(e -> {
            rentCar(txtCarId.getText(), txtName.getText(), txtContact.getText(), txtStartDate.getText());
        });
        return panel;
    }

    private void rentCar(String carId, String customerName, String contact, String startDate) {
        String sqlRent = "INSERT INTO rentals (car_id, customer_name, contact, start_date) VALUES (?, ?, ?, ?)";
        String sqlUpdate = "UPDATE cars SET status = 'rented' WHERE id = ?";
        try (Connection conn = connect();
                PreparedStatement pstmtRent = conn.prepareStatement(sqlRent);
                PreparedStatement pstmtUpdate = conn.prepareStatement(sqlUpdate)) {
            // Start transaction
            conn.setAutoCommit(false);
            // Insert rental record
            pstmtRent.setString(1, carId);
            pstmtRent.setString(2, customerName);
            pstmtRent.setString(3, contact);
            pstmtRent.setDate(4, Date.valueOf(startDate));
            pstmtRent.executeUpdate();
            // Update car status
            pstmtUpdate.setString(1, carId);
            pstmtUpdate.executeUpdate();
            // Commit transaction
            conn.commit();
            JOptionPane.showMessageDialog(this, "汽车租出成功");
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "租出失败: " + e.getMessage());
        }
    }

    private JPanel createReturnPanel() {
        JPanel panel = new JPanel(new GridLayout(0, 2, 10, 10));
        JTextField txtCarId = new JTextField(), txtEndDate = new JTextField();
        JButton btnReturn = new JButton("归还");
        panel.add(new JLabel("汽车编号:"));
        panel.add(txtCarId);
        panel.add(new JLabel("归还日期:"));
        panel.add(txtEndDate);
        panel.add(btnReturn);
        btnReturn.addActionListener(e -> {
            returnCar(txtCarId.getText(), txtEndDate.getText());
        });
        return panel;
    }

    private void returnCar(String carId, String endDate) {
        String sql = "UPDATE rentals SET end_date = ?, total_rent = (SELECT daily_rent FROM cars WHERE id = ?) * DATEDIFF(?, start_date) WHERE car_id = ? AND end_date IS NULL";
        String sqlUpdate = "UPDATE cars SET status = 'available' WHERE id = ?";
        try (Connection conn = connect();
                PreparedStatement pstmt = conn.prepareStatement(sql);
                PreparedStatement pstmtUpdate = conn.prepareStatement(sqlUpdate)) {
            // Start transaction
            conn.setAutoCommit(false);
            // Update rental record
            pstmt.setDate(1, Date.valueOf(endDate));
            pstmt.setString(2, carId);
            pstmt.setDate(3, Date.valueOf(endDate));
            pstmt.setString(4, carId);
            pstmt.executeUpdate();
            // Update car status
            pstmtUpdate.setString(1, carId);
            pstmtUpdate.executeUpdate();
            // Commit transaction
            conn.commit();
            JOptionPane.showMessageDialog(this, "汽车归还成功");
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "归还失败: " + e.getMessage());
        }
    }

    private JPanel createSearchPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        JTextField txtSearch = new JTextField();
        JTextArea txtResults = new JTextArea();
        txtResults.setEditable(false);
        JButton btnSearch = new JButton("搜索");
        panel.add(txtSearch, BorderLayout.NORTH);
        panel.add(new JScrollPane(txtResults), BorderLayout.CENTER);
        panel.add(btnSearch, BorderLayout.SOUTH);
        btnSearch.addActionListener(e -> {
            search(txtSearch.getText(), txtResults);
        });
        return panel;
    }

    private void search(String keyword, JTextArea txtResults) {
        String sql = "SELECT * FROM rentals INNER JOIN cars ON rentals.car_id = cars.id WHERE car_id = ? OR customer_name LIKE ?";
        try (Connection conn = connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, keyword);
            pstmt.setString(2, "%" + keyword + "%");
            ResultSet rs = pstmt.executeQuery();
            StringBuilder results = new StringBuilder();
            while (rs.next()) {
                results.append("Rental ID: ").append(rs.getInt("rental_id")).append("\n");
                results.append("Car ID: ").append(rs.getString("car_id")).append("\n");
                results.append("Customer Name:").append(rs.getString("customer_name")).append("\n");
                results.append("Contact: ").append(rs.getString("contact")).append("\n");
                results.append("Start Date: ").append(rs.getDate("start_date")).append("\n");
                results.append("End Date: ").append(rs.getDate("end_date")).append("\n");
                results.append("Total Rent:").append(rs.getDouble("total_rent")).append("\n\n");
            }
            txtResults.setText(results.toString());
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "查询失败: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new CarRentalSystem());
    }
}